package com.dreamchaser.familydevice.util.system;

import com.alibaba.fastjson.JSON;
import com.dreamchaser.familydevice.annotation.WeChat;
import com.dreamchaser.familydevice.domain.dto.AccountDTO;
import com.dreamchaser.familydevice.exception.BusinessException;
import com.dreamchaser.familydevice.support.CurrentUserMethodArgumentResolver;
import com.dreamchaser.familydevice.util.QYWeChat.WeChatUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Component
@Aspect
public class WeChatNotice {
    @Autowired
    WeChatUtil sendWeChat;
    @Autowired
    CurrentUserMethodArgumentResolver currentUserMethodArgumentResolver;

    @Around("@annotation(com.dreamchaser.familydevice.annotation.WeChat)")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        WeChat weChat = method.getAnnotation(WeChat.class);
        String toUser = weChat.toUser();
        RestController controller = pjp.getTarget().getClass().getAnnotation(RestController.class);
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String message = weChat.message();
        Object obj = new Object();
        try {
            obj = pjp.proceed();
            if (weChat.isOnlyError()) {
                return obj;
            }
        } catch (BusinessException e) {
            obj = e.getMessage();
        } catch (Exception e) {
            if (controller != null) {
                message = "接口错误，接口:" + request.getRequestURI();
            }
            obj = e;
        }

        if (StringUtils.isEmpty(message)) {
            return obj;
        }
        if (StringUtils.isEmpty(weChat.toUser())) {
            String currentUser = (String) request.getAttribute("currentUser");
            if (StringUtils.isEmpty(currentUser)) {
                throw new BusinessException("未查询到用户信息");
            }
            AccountDTO accountDTO = currentUserMethodArgumentResolver.get(currentUser);
            toUser = accountDTO.getWeChartId();
        }
        sendWeChat.sendAgentMsg(toUser,weChat.agent().getAgentId(),message + "\n" + (obj == null ? "" : JSON.toJSONString(obj)));
        return obj;
    }

}
